package com.bp.hearthealth.pulse.lnapps.notification

import android.annotation.SuppressLint
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.IBinder
import android.widget.RemoteViews
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.NotificationCompat
import com.bp.hearthealth.pulse.lnapps.R
import com.bp.hearthealth.pulse.lnapps.ads.topon.interstitial_ad.TopOnInterAdManager
import com.bp.hearthealth.pulse.lnapps.ads.topon.open_ad.TopOnOpenAdManager
import com.bp.hearthealth.pulse.lnapps.bp_extension.LogUtil
import com.bp.hearthealth.pulse.lnapps.bp_extension.UIHelperBp
import com.bp.hearthealth.pulse.lnapps.bp_utils.Constants

class NotificationService : Service() {

    // 为不同的 PendingIntent 使用不同的请求码
    private val bloodPressureRequestCode = 0
    private val heartRateRequestCode = 1
    private val lifestyleRequestCode = 2
    private val healthRequestCode = 3
    private var isServiceRunning = false
    private val NOTIFICATION_ID = 1230123 // 通知ID
    private val CHANNEL_ID = "ResideNotificationChannel" // 通知渠道ID

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    override fun onDestroy() {
        isServiceRunning = false
        val notificationManager =
            getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.cancel(NOTIFICATION_ID)
        LogUtil.i("销毁服务")
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        LogUtil.i("服务是否存活 $isServiceRunning")
        if (isServiceRunning) {
            // 如果服务仍然存活，则不执行任何操作
            return START_REDELIVER_INTENT
        }
        isServiceRunning = true
        notifyCustomNotification() // 确保在此处调用通知方法，确保服务启动时立刻显示通知并成为前台服务
        return START_STICKY
    }

    override fun onCreate() {
        super.onCreate()
        notifyCustomNotification()
//        LogUtil.i("常驻服务:onCreate()")
    }

    override fun onTaskRemoved(rootIntent: Intent?) {
        TopOnOpenAdManager.releaseOpenAd()
        TopOnInterAdManager.releaseManualLoadInterstitialAd()
        super.onTaskRemoved(rootIntent)
        LogUtil.i("常驻服务：onTaskRemoved()")
//        stopSelf()
    }

    @SuppressLint("RemoteViewLayout", "DiscouragedApi")
    fun notifyCustomNotification() {
        val context = ForegroundActivityManager.getCurrentActivity() ?: return
        // 创建一个自定义通知布局
        val notificationLayout =
            RemoteViews(context.packageName, R.layout.resident_service_small_layout)
        val notificationLayoutExpanded =
            RemoteViews(context.packageName, R.layout.resident_service_big_layout)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val mChannel = NotificationChannel(
                CHANNEL_ID,
                UIHelperBp.getString(R.string._app_name_str_bp),
                NotificationManager.IMPORTANCE_HIGH
            )
            mChannel.description = "descriptionText"
            val notificationManager =
                context.getSystemService(AppCompatActivity.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannel(mChannel)
            val intent = Intent(context, NotificationClickActivity::class.java)

            //血压
            val bloodPressurePendingIntent: PendingIntent? =
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                    PendingIntent.getActivity(
                        context,
                        bloodPressureRequestCode,
                        intent.putExtra(
                            Constants.NOTIFICATION_ACTION,
                            Constants.NOTIFICATION_BLOOD_PRESSURE
                        ),
                        PendingIntent.FLAG_IMMUTABLE
                    )
                } else {
                    PendingIntent.getActivity(
                        context,
                        bloodPressureRequestCode,
                        intent.putExtra(
                            Constants.NOTIFICATION_ACTION,
                            Constants.NOTIFICATION_BLOOD_PRESSURE
                        ),
                        PendingIntent.FLAG_ONE_SHOT or PendingIntent.FLAG_IMMUTABLE
                    )
                }

            notificationLayout.setOnClickPendingIntent(
                R.id.iv_blood_pressure, bloodPressurePendingIntent
            )
            notificationLayoutExpanded.setOnClickPendingIntent(
                R.id.iv_blood_pressure, bloodPressurePendingIntent
            )

            //心率
            val heartRatePendingIntent: PendingIntent? =
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                    PendingIntent.getActivity(
                        context,
                        heartRateRequestCode,
                        intent.putExtra(
                            Constants.NOTIFICATION_ACTION,
                            Constants.NOTIFICATION_HEART_RATE_GUIDE
                        ),
                        PendingIntent.FLAG_IMMUTABLE
                    )
                } else {
                    PendingIntent.getActivity(
                        context,
                        heartRateRequestCode,
                        intent.putExtra(
                            Constants.NOTIFICATION_ACTION,
                            Constants.NOTIFICATION_HEART_RATE_GUIDE
                        ),
                        PendingIntent.FLAG_ONE_SHOT or PendingIntent.FLAG_IMMUTABLE
                    )
                }
            notificationLayout.setOnClickPendingIntent(R.id.iv_heart_rate, heartRatePendingIntent)
            notificationLayoutExpanded.setOnClickPendingIntent(
                R.id.iv_heart_rate, heartRatePendingIntent
            )

            //Lifestyle
            val lifestylePendingIntent: PendingIntent? =
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                    PendingIntent.getActivity(
                        context,
                        lifestyleRequestCode,
                        intent.putExtra(
                            Constants.NOTIFICATION_ACTION,
                            Constants.NOTIFICATION_LIFESTYLE_FRAGMENT
                        ),
                        PendingIntent.FLAG_IMMUTABLE
                    )
                } else {
                    PendingIntent.getActivity(
                        context,
                        lifestyleRequestCode,
                        intent.putExtra(
                            Constants.NOTIFICATION_ACTION,
                            Constants.NOTIFICATION_LIFESTYLE_FRAGMENT
                        ),
                        PendingIntent.FLAG_ONE_SHOT or PendingIntent.FLAG_IMMUTABLE
                    )
                }
            notificationLayout.setOnClickPendingIntent(R.id.iv_lifestyle, lifestylePendingIntent)
            notificationLayoutExpanded.setOnClickPendingIntent(
                R.id.iv_lifestyle, lifestylePendingIntent
            )

            //首页
            val healthPendingIntent: PendingIntent? =
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                    PendingIntent.getActivity(
                        context,
                        healthRequestCode,
                        intent.putExtra(
                            Constants.NOTIFICATION_ACTION,
                            Constants.NOTIFICATION_HOME_FRAGMENT
                        ),
                        PendingIntent.FLAG_IMMUTABLE
                    )
                } else {
                    PendingIntent.getActivity(
                        context,
                        healthRequestCode,
                        intent.putExtra(
                            Constants.NOTIFICATION_ACTION,
                            Constants.NOTIFICATION_HOME_FRAGMENT
                        ),
                        PendingIntent.FLAG_ONE_SHOT or PendingIntent.FLAG_IMMUTABLE
                    )
                }
            notificationLayout.setOnClickPendingIntent(R.id.iv_home_fragment, healthPendingIntent)
            notificationLayoutExpanded.setOnClickPendingIntent(
                R.id.iv_home_fragment, healthPendingIntent
            )
            val vibrationPattern = longArrayOf() // 设置为空数组，不应用任何震动模式

            val notification = NotificationCompat.Builder(context, CHANNEL_ID)
                .setSmallIcon(R.mipmap.notification_test)
                .setStyle(NotificationCompat.DecoratedCustomViewStyle())
                .setContentIntent(healthPendingIntent)
                .setCustomContentView(notificationLayout)
                .setVisibility(NotificationCompat.VISIBILITY_SECRET)
                .setOngoing(true)//持续显示
                .setAutoCancel(false)//禁止通知被点击后自动取消
                .setVibrate(vibrationPattern)
                .setPriority(NotificationCompat.PRIORITY_MAX)
                .setCustomBigContentView(notificationLayoutExpanded)
                .build()
            notificationManager.notify(NOTIFICATION_ID, notification)
            // 将服务设置为前台服务
            startForeground(NOTIFICATION_ID, notification)
        }
    }
}
